package com.cman777.springc.common.helper;

import com.baomidou.mybatisplus.annotation.TableId;
import com.cman777.springc.common.bean.Iface.EntityIFace;
import com.cman777.springc.common.bean.enums.BaseResultCodeEnum;
import com.cman777.springc.common.bean.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.Collection;

/**
 * @author chenzhicong
 * @time 2019/11/9 15:17
 * @description
 */
public class EntityUtil {
    /**
     * 实体类的主键的redis key的前缀
     */
    private static final String ENTITY_SEQUENCE_REDIS_PREFIX = "SEQ_";
    /**
     * 获取实体类的主键的redis key
     * @param entityClazz
     * @return SEQ_ + 实体类名
     */
    public static String getIdRedisKey(@NotNull Class entityClazz) {
        return ENTITY_SEQUENCE_REDIS_PREFIX + entityClazz.getSimpleName();
    }

    /**
      * 获取实体主键字段名称
      */
    public static <T extends EntityIFace> String getEntityIdColumnName(@NotNull Class<T> entityClazz){
        Collection<Field> fields = BeanUtil.getDeclaredFields(entityClazz);
        TableId idsTableId = null;
        for (Field field : fields) {
            TableId tableId = field.getAnnotation(TableId.class);
            if(tableId != null){
                if(idsTableId != null){
                    throw new BusinessException(BaseResultCodeEnum.SYSTEM_ERROR);
                }
                idsTableId = tableId;
            }
        }
        if(idsTableId == null){
            throw new BusinessException(BaseResultCodeEnum.SYSTEM_ERROR);
        }
        String idColumnName = idsTableId.value();
        if(StringUtils.isBlank(idColumnName)){
            throw new BusinessException(BaseResultCodeEnum.SYSTEM_ERROR);
        }else{
            return idColumnName;
        }

    }





}
